<template>
  <div>
    <van-search
      ref="search"
      v-model="value"
      shape="round"
      background="#1989fa"
      placeholder="请输入搜索关键词"
      autofocus=true
      v-focus
      @input="sarchr"
      @search="jump"
    >
      <template #left>
        <van-icon
          name="arrow-left"
          @click="onClickLeft"
        />
      </template>
    </van-search>
    <!-- 历史 -->
    <History
      v-show="arr.length==0||value==''"
      :val='value'
      :jump='jump'
    ></History>
    <!-- 搜索展示 -->
    <Exhibition
      v-show="value!==''"
      :arr='arr'
      :val='value'
    ></Exhibition>
  </div>
</template>

<script>
import { getSearchInformation } from '@/api/home.js'
import History from './history/index.vue'
import Exhibition from './Exhibition/index.vue'

// 导入局部组件必须在scrip里面导入,在App里面导入
export default {
  // 组件名称
  name: 'erar1',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 接收局部注册的组件
  components: {
    History,
    Exhibition
  },
  // 组件数据
  data () {
    return {
      value: '', //输入的搜索文字
      arr: [], //联想菜单列表
      timerId: null,
    }
  },
  methods: {
    // 带参数跳转页面
    jump () {
      this.$router.push(`/search/${this.value}`)
      this.value = ''
    },
    onClickLeft () {
      this.$router.push({
        path: '/layout/home'
      })
    },
    // 搜索
    sarchr () {
      //关闭上一次的延时器
      if (this.timerId) {
        clearTimeout(this.timerId)
      }
      // 去除空格
      this.timerId = setTimeout(async () => {
        if (this.value != '') {
          const arr = await getSearchInformation(this.value)
          const { options } = arr.data.data
          this.arr = options.map(str => str.replace(/ /g, ''))
        }
      }, 350);
    }
  },
  activated () {
    this.$refs.search.querySelector('input[type=search]').focus()
  }
}
</script>
<style lang='less' scoped>
.van-icon-arrow-left {
  color: #fff;
  font-size: 22px;
  margin-right: 10px;
}
</style>
